//
//  ProductDetailViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "SyncImageView.h"
#import "AppDelegate.h"
#import "ShoppingViewController.h"
#import "MainViewController.h"
#import "Place.h"
#import "StoreData.h"
#import "MapViewController.h"

@implementation ProductDetailViewController
@synthesize rootView;
@synthesize product;
@synthesize brand;
@synthesize name;
@synthesize introduction;
@synthesize brandName;
@synthesize color;
@synthesize item;
@synthesize fabric;

@synthesize shopping;
@synthesize store;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        gpsHelper = [[GPSHelper alloc] init];
        gpsHelper.delegate = self;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [rootView release];
    [name release];
    [introduction release];
    [brandName release];
    [color release];
    [item release];
    [fabric release];
    [shopping release];
    [store release];
    [brand release];
    [product release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //[(MainViewController *)mainViewController showHeadView];
    int y = 0;
    NSString *imageUrl = brand.logo;
    //NSLog(@"logo=%@", imageUrl);
    SyncImageView *logoView = [[SyncImageView alloc] initWithUrl:imageUrl andRequestQueue:requestQueue];
    logoView.frame = CGRectMake(98, y, 124, 64);
    [rootView addSubview:logoView];
    [logoView release];
    y += 64;
    
    name.text = [NSString stringWithFormat:@"%@ %@", product.name, product.item];
    name.frame = CGRectMake(10, y, 300, 24);
    y += 24;
    
    y += 5;
    introduction.text = product.introduction;
    NSInteger contentHeight = [product getContentHeight];
    introduction.font = [product getFont];
    introduction.frame = CGRectMake(10, y, 300, contentHeight);
    introduction.numberOfLines = [product getLineNumbers];
    y += contentHeight;
    
    brandName.text = [NSString stringWithFormat:@"%@：%@", 
                      [AppDelegate getLanguageString:@"product_brand"],
                      brand.name];
    brandName.frame = CGRectMake(10, y, 130, 16);
    
    item.text = [NSString stringWithFormat:@"%@：%@", 
                      [AppDelegate getLanguageString:@"product_item"],
                      product.item];
    item.frame = CGRectMake(160, y, 130, 16);
    y += 16;
    
    color.text = [NSString stringWithFormat:@"%@：%@", 
                      [AppDelegate getLanguageString:@"product_color"],
                      product.color];
    color.frame = CGRectMake(10, y, 130, 16);
    
    fabric.text = [NSString stringWithFormat:@"%@：%@", 
                 [AppDelegate getLanguageString:@"product_fabric"],
                 product.fabric];
    fabric.frame = CGRectMake(160, y, 130, 16);
    y += 16;
    
    y += 5;
    shopping.frame = CGRectMake(90, y, 61, 24);
    [shopping setTitle:[AppDelegate getLanguageString:@"product_shopping"] forState:UIControlStateNormal];
    store.frame = CGRectMake(160, y, 70, 24);
    [store setTitle:[AppDelegate getLanguageString:@"product_store"] forState:UIControlStateNormal];
    y += 24;
    
    y += 10;
    NSString *productImgs = product.iPhoneImages;
    //NSLog(@"productImgs=%@", productImgs);
    NSArray *images = [productImgs componentsSeparatedByString: @"|"];
    for (NSString *imgInfo in images) {
        NSArray *infos = [imgInfo componentsSeparatedByString:@","];
        NSString *imagePath = [infos objectAtIndex:0];
        NSInteger imageHeight = [[infos objectAtIndex:1] intValue] / 2;
        SyncImageView *imageView = [[SyncImageView alloc] initWithUrl:imagePath andRequestQueue:requestQueue];
        imageView.frame = CGRectMake(0, y, 320, imageHeight);
        [rootView addSubview:imageView];
        [imageView release];
        y += imageHeight;
    }
    rootView.contentSize = CGSizeMake(320, y);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)goShopping:(id)sender {
    ShoppingViewController *shopView = [[ShoppingViewController alloc] initWithNibName:@"ShoppingViewController" bundle:nil];
    shopView.product = product;
    [(MainViewController *)mainViewController pushViewController:shopView];
    [shopView release];
}

- (IBAction)goStore:(id)sender {
    /*
    StoreViewController *storeView = [[StoreViewController alloc] initWithNibName:@"StoreViewController" bundle:nil];
    storeView.brandData = brand;
    [(MainViewController *)mainViewController pushViewController:storeView];
    [storeView release];
     */
    [gpsHelper startLocation];
}

- (NSArray *)initNearStores:(CLLocationCoordinate2D)coordinate {
	CLLocation *locationCoordinate = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    NSArray *allStores = [StoreData getItemsByBrandId:[self.brand.brandID intValue]];
    NSInteger minDistance = 9999 * 1000;
    StoreData *minStoreData = nil;
    for (StoreData *data in allStores) {
        CLLocation *dataCoordinate = [[CLLocation alloc] initWithLatitude:[data.latitude floatValue] longitude:[data.longitude floatValue]];
        NSInteger distance = (NSInteger)[locationCoordinate distanceFromLocation:dataCoordinate];
        //NSLog(@"id(%@) distance=%d", data.storeID, distance);
        if (distance < minDistance) {
            minDistance = distance;
            minStoreData = data;
        }
        [dataCoordinate release];
    }
    [locationCoordinate release];
    
    NSMutableArray *nearStores = [[[NSMutableArray arrayWithCapacity:5] retain] autorelease];
    if (minStoreData != nil) {
        NSInteger maxDistance = 1000 * 10;//10Km
        CLLocation *locationCoordinate = [[CLLocation alloc] initWithLatitude:[minStoreData.latitude floatValue] longitude:[minStoreData.longitude floatValue]];
        for (StoreData *data in allStores) {
            CLLocation *dataCoordinate = [[CLLocation alloc] initWithLatitude:[data.latitude floatValue] longitude:[data.longitude floatValue]];
            NSInteger distance = (NSInteger)[locationCoordinate distanceFromLocation:dataCoordinate];
            //NSLog(@"id(%@) distance=%d", data.storeID, distance);
            if (distance < maxDistance) {
                [nearStores addObject:data];
            }
            [dataCoordinate release];
        }
        [locationCoordinate release];
    }
    return nearStores;
}

- (void)jumpToMapView:(NSArray *)places local:(CLLocationCoordinate2D)coordinate {
    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapViewController.places = places;
    mapViewController.location = [[[Place alloc] initWithLatitude:coordinate.latitude andlongitude:coordinate.longitude andTitle:nil andDetail:nil] autorelease];
    MainViewController *mainView = (MainViewController *)mainViewController;
    [mainView pushViewController:mapViewController];
    [mapViewController release];
}

- (void)updataHeading:(CLLocationDirection)heading {
    ;
}

- (void)updataLocation:(CLLocationCoordinate2D)coordinate {
    [gpsHelper stopLocation];
    NSArray *nearStores = [self initNearStores:coordinate];
    NSMutableArray *places = [NSMutableArray arrayWithCapacity:[nearStores count]];
    for (StoreData *data in nearStores) {
        Place *p = [[Place alloc] initWithLatitude:[data.latitude floatValue] andlongitude:[data.longitude floatValue] andTitle:data.name andDetail:nil];
        [places addObject:p];
        [p release];
    }
    [self jumpToMapView:places local:coordinate];
}

@end
